<?php
require_once '_utils/common.php';
require_once '_utils/database.php';

if (isset($_GET['project']))
	$activeTab = 'project';
else if (isset($_GET['job']))
	$activeTab = 'job';
else
	$activeTab = 'person';

session_start();
$loggedIn = !empty($_SESSION['admin']);

if (!empty($_POST['password'])) {
	if ($_POST['password'] == 'Lrrr') {
		$_SESSION['admin'] = 1;
		$loggedIn = true;
		Header('Location: '.getBasePath().'/admin');
	} else $loginError = "<div class='loginError'>WRONG!!!</div>";
}
if (isset($_GET['logout'])) {
	unset($_SESSION['admin']);
	$loggedIn = false;
	Header('Location: '.getBasePath());
}




if ($loggedIn) {
	if (isset($_POST['action']))
		open_db();
	if ($_POST['action'] == 'add_person' || $_POST['action'] == 'update_person' || $_POST['action'] == 'search_person' || $_POST['action'] == 'delete_person') {
		$person_id = cleanq(@$_POST['person_id']);
		$name = cleanq("$_POST[lname], $_POST[fname]");
		$bdate = empty($_POST['birth_year']) || empty($_POST['birth_month']) || empty($_POST['birth_day']) ?
			'NULL' : cleanq("$_POST[birth_year]-$_POST[birth_month]-$_POST[birth_day]");
		$ddate = empty($_POST['death_year']) || empty($_POST['death_month']) || empty($_POST['death_day']) ?
			'NULL' : cleanq("$_POST[death_year]-$_POST[death_month]-$_POST[death_day]");
		$photo_url = empty($_POST['photo_url']) ? 'NULL' : cleanq($_POST['photo_url']);
	} else if ($_POST['action'] == 'add_project' || $_POST['action'] == 'update_project' || $_POST['action'] == 'search_project' || $_POST['action'] == 'delete_project') {
		$project_id = cleanq(@$_POST['project_id']);
		$release_date = empty($_POST['month']) || empty($_POST['day']) ?
			'NULL' : cleanq("$_POST[year]-$_POST[month]-$_POST[day]");
		if (empty($_POST['votes']) || empty($_POST['rating'])) {
			$votes = 'NULL';
			$rating = 'NULL';
		} else {
			$votes = cleanq($_POST['votes']);
			$rating = cleanq($_POST['rating']);
		}
		if ($_POST['medium'] == 'television' || $_POST['medium'] == 'mini')
			$title = '\'"'.clean($_POST['title']).'"\'';
		else
			$title = cleanq($_POST['title']);
		$year = cleanq($_POST['year']);
		$episode = cleanq($_POST['episode']);
		$other = $_POST['medium'] == 'movie' || $_POST['medium'] == 'television' ? "''" : cleanq($_POST['medium']);
	} else if ($_POST['action'] == 'add_job' || $_POST['action'] == 'delete_job') {
		$other = $_POST['medium'] == 'movie' || $_POST['medium'] == 'television' ? "''" : cleanq($_POST['medium']);
		if ($_POST['medium'] == 'television' || $_POST['medium'] == 'mini')
			$title = '\'"'.clean($_POST['title']).'"\'';
		else
			$title = cleanq($_POST['title']);
		$year = cleanq($_POST['year']);
		$episode = cleanq($_POST['episode']);
		$name = cleanq("$_POST[lname], $_POST[fname]");
		$job_title = cleanq($_POST['job_title']);
		$billing_position = cleanq($_POST['billing_position']);
	}
	if ($_POST['action'] == 'add_person' && !empty($_POST['fname']) && !empty($_POST['lname'])) {
		if (mysql_query("insert into persons values (null, $name, $bdate, $ddate, $photo_url)")) {
			$new_person = @mysql_fetch_array(mysql_query("select * from persons where person_id='".mysql_insert_id()."'"));
			$person_info['msg'] = "Successfully added <a href='".getBasePath()."/person/$new_person[person_id]'>$new_person[name]</a>!";
		} else
			$person_info['msg'] = "Failed adding person!";
	} else if ($_POST['action'] == 'update_person' && !empty($_POST['fname']) && !empty($_POST['lname'])) {
		if (@mysql_query("update persons set name=$name, birth_date=$bdate, death_date=$ddate, photo_url=$photo_url where person_id=$person_id")) {
			$person = @mysql_fetch_array(mysql_query("select * from persons where person_id=$person_id"));
			$person_info['msg'] = "Successfully updated <a href='".getBasePath()."/person/$person[person_id]'>$person[name]</a>!";
		} else
			$person_info['msg'] = "Failed updating person!";
	} else if ($_POST['action'] == 'search_person' && !empty($_POST['fname']) && !empty($_POST['lname'])) {
		$result = mysql_query("select * from persons where name=$name");
		if (mysql_num_rows($result) > 0)
			$person_info = mysql_fetch_array($result);
		else
			$person_info['error'] = "\"$_POST[fname] $_POST[lname]\" not found!";
	} else if ($_POST['action'] == 'delete_person' && !empty($_POST['person_id'])) {
		if (mysql_query("delete from persons where person_id=$person_id")) {
			$person_info['msg'] = "Successfully deleted $name!";
			mysql_query("delete from jobs where person_id=$person_id");
		} else
			$person_info['msg'] = "Failed deleting <a href='".getBasePath()."/person/$_POST[person_id]'>$name</a>!";



	} else if ($_POST['action'] == 'add_project' && !empty($_POST['title']) && !empty($_POST['year'])) {
		$query = "insert into projects values (null, $title, $year, $episode, $other, $votes, $rating, $release_date)";
		if (mysql_query($query)) {
			$project_id = mysql_insert_id();
			foreach ($_POST['genres'] as $genre)
				mysql_query("insert into genres values ('$project_id', '".clean($genre)."')");
			$project_info['msg'] = "Successfully added project $title!";
		} else
			$project_info['msg'] = "Failed adding project!";
	} else if ($_POST['action'] == 'update_project' && !empty($_POST['title']) && !empty($_POST['year'])) {
		if (mysql_query("update projects set title=$title, year=$year, episode=$episode, other=$other, votes=$votes, rating=$rating, usa_release_date=$release_date where project_id=$project_id")) {
			$project = mysql_fetch_array(mysql_query("select * from projects where project_id=$project_id"));
			$project_info['msg'] = "Successfully updated $project[title]!";
			mysql_query("delete from genres where project_id=$project_id");
			foreach ($_POST['genres'] as $genre)
				mysql_query("insert into genres values($project_id, '".clean($genre)."')");
		} else
			$project_info['msg'] = "Failed updating project!";
	} else if ($_POST['action'] == 'search_project' && !empty($_POST['title']) && !empty($_POST['year'])) {
		$result = mysql_query("select * from projects where title=$title and year=$year and other=$other and episode=$episode");
		if (mysql_num_rows($result) > 0) {
			$project_info = mysql_fetch_array($result);
			$project_info['genres'] = array();
			$result = mysql_query("select distinct genre from genres where project_id=$project_info[project_id]");
			while ($genre = mysql_fetch_row($result))
				$project_info['genres'][] = $genre[0];
		} else
			$project_info['error'] = "Unable to find project!";
	} else if ($_POST['action'] == 'delete_project' && !empty($_POST['project_id'])) {
		if (mysql_query("delete from projects where project_id=$project_id")) {
			$project_info['msg'] = "Successfully deleted $_POST[title]!";
			mysql_query("delete from jobs where project_id=$project_id");
		} else
			$project_info['msg'] = "Failed deleting $_POST[title]!";

	} else if ($_POST['action'] == 'add_job') {
		$errors = array();
		$person = mysql_query("select person_id from persons where name=$name");
		if (mysql_num_rows($person) == 0) $errors[] = "Person does not exist!";
		else $person = mysql_fetch_array($person);
		$project = mysql_query("select project_id from projects where title=$title and year=$year and episode=$episode and other=$other");
		if (mysql_num_rows($project) == 0) $errors[] = "Project does not exist!";
		else $project = mysql_fetch_array($project);
		if (count($errors) > 0) $job_info['msg'] = implode('<br/>', $errors);
		else if (mysql_num_rows(mysql_query("select * from jobs where project_id=$project[project_id] and person_id=$person[person_id] and job_title=$job_title")) > 0)
			$job_info['msg'] = "Failed adding job! Job already exists!";
		else if (mysql_query("insert into jobs values ('$project[project_id]', '$person[person_id]', $job_title, $billing_position)"))
			$job_info['msg'] = "Successfully added job!";
		else
			$job_info['msg'] = "Failed adding job!".mysql_error();
	} else if ($_POST['action'] == 'delete_job') {
		$errors = array();
		$person = mysql_query("select person_id from persons where name=$name");
		if (mysql_num_rows($person) == 0) $errors[] = "Person does not exist!";
		else $person = mysql_fetch_array($person);
		$project = mysql_query("select project_id from projects where title=$title and year=$year and episode=$episode and other=$other");
		if (mysql_num_rows($project) == 0) $errors[] = "Project does not exist!";
		else $project = mysql_fetch_array($project);
		if (count($errors) > 0) $job_info['msg'] = implode('<br/>', $errors);
		else if (mysql_num_rows(mysql_query("select * from jobs where project_id=$project[project_id] and person_id=$person[person_id] and job_title=$job_title")) == 0)
			$job_info['msg'] = "Failed deleting job! Job doesn't exist!";
		else if (mysql_query("delete from jobs where project_id=$project[project_id] and person_id=$person[person_id] and job_title=$job_title"))
			$job_info['msg'] = "Successfully deleted job!";
		else
			$job_info['msg'] = "Failed deleting job!";
	}
}
?>

<html>
<head>
<title>Admin Panel - Movie Data Analyzer</title>
<link rel="stylesheet" type="text/css" href="_css/main.css" media="screen" />
<link rel="stylesheet" type="text/css" href="_css/admin.css" media="screen" />
</head>
<body>
<div id="main_block">
	<div id="header_block"><div id="admin_title">Admin Panel</div></div>
	<div class="clearer"></div>

<? if (!$loggedIn): ?>

	<div id='loginForm'>
		<form method='post' action='<?=getBasePath()?>/admin.php'>
			<input type='password' name='password'/>
		</form>
		<?=@$loginError?>
	</div>

<? else: ?>
	<div id='adminLogout'><a href='<?=getBasePath()?>/admin.php?logout'>Log out</a></div>
	<div id="link_bar">
		<a <?php if ($activeTab == 'person') echo "class='current_page'"?> href="admin?person">Person</a> | 
		<a <?php if ($activeTab == 'project') echo "class='current_page'"?> href="admin?project">Project</a> | 
		<a <?php if ($activeTab == 'job') echo "class='current_page'"?> href="admin?job">Job</a>
	</div>
	<div class="clearer"></div>
	<div id="add_block">
<?	require_once "_utils/adminPanel.php";

	if ($activeTab == 'person')
		createAddPersonFields(@$person_info);
	else if ($activeTab == 'project')
		createAddProjectFields(@$project_info);
	else if ($activeTab == 'job')
		createAddJobFields(@$job_info);
?>
	</div>
<? endif; ?>
</div>
<? require 'footer.php'; ?>
	</body>
</html>

